package com.zhu.app.dwd;

import com.zhu.utils.ZhuKafkaUtil;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

/**
 * 用户收藏商品时业务数据库的收藏表会插入一条数据，因此筛选操作类型为 insert 的
 * 数据即可
 */
public class DWDInteractionFavorAddApp {

    public static void main(String[] args) throws Exception {

        //todo env
        StreamExecutionEnvironment streamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment();
        streamExecutionEnvironment.setParallelism(1); //  kafka partition 4

        //check point
           /*
        streamExecutionEnvironment.setStateBackend(new HashMapStateBackend());
        streamExecutionEnvironment.getCheckpointConfig().setCheckpointStorage(ClusterParametersConfig.HDFS_CHECKPOINT_FILE_DIR);  //检查点保存在hdfs
        System.setProperty("HADOOP_USER_NAME", "zhu");
        streamExecutionEnvironment.getCheckpointConfig().setCheckpointTimeout(10 * 60000L);  //TimeOut
        streamExecutionEnvironment.getCheckpointConfig().setMaxConcurrentCheckpoints(2);  //最大共存检查点
        streamExecutionEnvironment.setRestartStrategy(RestartStrategies.fixedDelayRestart(3, 5 * 1000L));  //重启策略
        */
        StreamTableEnvironment streamTableEnvironment = StreamTableEnvironment.create(streamExecutionEnvironment);
        Configuration configuration = streamTableEnvironment.getConfig().getConfiguration();
     //   configuration.setString("table.exec.state.ttl", "5 s");  //状态存活时间

        streamTableEnvironment.executeSql(ZhuKafkaUtil.getTopicDB("dwd_interaction_favor_add"));
        // TODO 4. 读取收藏表数据
        Table favorInfo = streamTableEnvironment.sqlQuery("select\n" +
                        "data['id'] id,\n" +
                        "data['user_id'] user_id,\n" +
                        "data['sku_id'] sku_id,\n" +
                        "date_format(data['create_time'],'yyyy-MM-dd') date_id,\n" +
                "data['create_time'] create_time \n" +
                        "from topic_db\n" +
                        "where `table` = 'favor_info'\n" +
                        "and `type` = 'insert'\n");
        streamTableEnvironment.createTemporaryView("favor_info", favorInfo);
// TODO 5. 创建 Kafka-Connector dwd_interaction_favor_add 表
        streamTableEnvironment.executeSql("create table dwd_interaction_favor_add (\n" +
        "id string,\n" +
                "user_id string,\n" +
                "sku_id string,\n" +
                "date_id string,\n" +
                "create_time string\n" +
                ")" +
                ZhuKafkaUtil.getKafkaSinkDDL("dwd_interaction_favor_add"));
// TODO 6. 将数据写入 Kafka-Connector 表
        streamTableEnvironment.executeSql("" +
                        "insert into dwd_interaction_favor_add select * from favor_info");

    }
}
